import axios from 'axios';
import { getStorage, removeStorage } from './storage';

const request = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

request.interceptors.request.use(
  (config) => {
    const token = getStorage('token');
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

request.interceptors.response.use(
  (response) => {
    // 对响应数据进行操作
    return response.data;
  },
  (err) => {
    // 对响应错误进行操作
    // token失效
    if (err?.response?.status === 401) {
      const removeKey = ['token', 'refresh_token', 'userInfo'];
      removeKey.forEach((key) => {
        removeStorage(key);
      });
      // 强制刷新，跳转到登录页
      window.location.reload();
    }
    return Promise.reject(err);
  }
);

export { request };
